// 引入路由
const router = require('koa-router')()
// 引入数据库操作
const {
  wxUser,
  user,
  subscribe,
  activity,
  userAndActivity,
  goods,
  opinion,
  graph,
  integral,
  classify,
  scan
} = require('../db/index')
// 引入网络请求
const axios = require('axios')
const { isValidObjectId } = require('mongoose')
// 引入保存网络图片到本地工具
const {saveBase64Image} = require('../utils/saveImg')
const fs = require('fs')

// excel工具
const Excel = require('exceljs')

/**  路由  **/
// (页面路由)
// 登录页
router.get('/', async (ctx)=>{
  ctx.response.redirect('/login')
})
router.get('/login',async (ctx) => {
  await ctx.render('login')
})
// 首页
router.get('/index',async ctx => {
  await ctx.render('index')
})
// 用户
router.get('/user',async ctx => {
  await ctx.render('user')
})
// 预约
router.get('/subscribe',async ctx => {
  await ctx.render('subscribe')
})
// 活动
router.get('/activity',async ctx => {
  await ctx.render('activity')
})
// 积分
router.get('/integral',async ctx => {
  await ctx.render('integral')
})
// 意见
router.get('/opinion',async ctx => {
  await ctx.render('opinion')
})
// 商品
router.get('/goods',async ctx => {
  await ctx.render('goods')
})
// 轮播图
router.get('/graph',async ctx => {
  await ctx.render('graph')
})
// 扫描
router.get('/scan',async ctx => {
  await ctx.render('scan')
})
// 分类
router.get('/classify',async ctx => {
  await ctx.render('classify')
})



/* 常量 */
// const baseUrl = 'http://zhs.liaoxiaohei.online'
const baseUrl = 'http://127.0.0.1'


// (数据请求)
// 后台登录
router.post('/request/backLogin', async (ctx)=>{
  let data = ctx.request.body
  let result = await user.findUser({name: data.name})
  if (result.length !== 0 && data.password === result[0].password) {
    ctx.body = JSON.stringify({code: 200,message: '成功'})
  }else{
    ctx.body = JSON.stringify({code: 506,message: '账户名或者密码错误'})
  }
})
// 增加后台用户
router.post('/request/saveUser', async (ctx)=>{
  let data = ctx.request.body
  const result = await user.saveUser(data)
  ctx.body = JSON.stringify({code: 200,message: '创建后台用户成功'})
})

// 获取微信用户列表
router.get('/request/getWxUser', async ctx => {
  const result = await wxUser.findWxUser({})
   ctx.body = JSON.stringify({code: 200, userList: result})
})
// 更新微信用户（绑定学籍）
router.post('/request/updateWxUser', async ctx => {
  let data = ctx.request.body
  let result = await wxUser.updateWxUser({_id: data.userId},{studentId: data.studentId,name: data.name})
  if (result.acknowledged) {
    ctx.body = JSON.stringify({code: 200, message: '绑定学籍成功'})
  }else {
    ctx.body = JSON.stringify({code: 506, message: '绑定学籍失败'})
  }
})

// 获取预约列表
router.get('/request/getSubscribe', async ctx => {
  const subscribeResult = await subscribe.findSubscribe({})
  for(const item of subscribeResult) {
    item.nickName = (await wxUser.findWxUser({id: item.id}))[0].nickName
  }
   ctx.body = JSON.stringify({code: 200, subscribeList: subscribeResult})
})
// 发起预约
router.post('/request/saveSubscribe', async ctx => {
  const data = ctx.request.body
  const result = await subscribe.saveSubscribe(data)
   ctx.body = JSON.stringify({code: 200, message: '预约成功'})
})

// 发布活动
router.post('/request/saveActivity', async ctx => {
  const data = ctx.request.body
  // 随机数作为图片保存的名字
  const range1 = parseInt(Math.random() * 10**10)
  const range2 = parseInt(Math.random() * 10**10)
  const range3 = parseInt(Math.random() * 10**10)
  // 获取图片类型
  const type1 = data.img1.match(/data:image\/(.+);base64,/)[1]
  const type2 = data.img2.match(/data:image\/(.+);base64,/)[1]
  const type3 = data.img3.match(/data:image\/(.+);base64,/)[1]
  // 保存图片到本地
  saveBase64Image(data.img1,'./static/images/activityImages/',range1+'.'+type1)
  saveBase64Image(data.img2,'./static/images/activityImages/',range2+'.'+type2)
  saveBase64Image(data.img3,'./static/images/activityImages/',range3+'.'+type3)
  // 转换名字
  data.img1 = range1+'.'+type1
  data.img2 = range2+'.'+type2
  data.img3 = range3+'.'+type3
  // 添加状态
  data.status = 0
  // 保存进入数据库
  const result = activity.saveActivity(data)
  ctx.body = JSON.stringify({code: 200, message: '发布成功'})
})
// 获取活动列表
router.get('/request/getActivity', async ctx => {
  const result = await activity.findActivity({})
  for (let item of result) {
    item.nickName = (await wxUser.findWxUser({id:item.userId}))[0].nickName
    item.img1 = baseUrl + '/images/activityImages/'+ item.img1
    item.img2 = baseUrl + '/images/activityImages/'+ item.img2
    item.img3 = baseUrl + '/images/activityImages/'+ item.img3
  }
  ctx.body = JSON.stringify({code: 200, activityList: result})
})
router.post('/request/getActivity', async ctx => {
  const data = ctx.request.body
  const result = await activity.findActivity(data)
  for (let item of result) {
    item.nickName = (await wxUser.findWxUser({id:item.userId}))[0].nickName
    item.img1 = baseUrl + '/images/activityImages/'+ item.img1
    item.img2 = baseUrl + '/images/activityImages/'+ item.img2
    item.img3 = baseUrl + '/images/activityImages/'+ item.img3
  }
  ctx.body = JSON.stringify({code: 200, activityList: result})
})
// 参加活动
router.post('/request/saveUserAndActivity', async ctx => {
  const data = ctx.request.body
  const result = await userAndActivity.findUserAndActivity(data)

  if (result.length === 0) {
    const temp = await userAndActivity.saveUserAndActivity(data)
    ctx.body = JSON.stringify({code: 200, message: '报名成功'})
  }else {
    ctx.body = JSON.stringify({code: 506, message: '你已报名，无需重新报名'})
  }
})
// 获取我参加的
router.post('/request/getJoin', async ctx => {
  const data = ctx.request.body
  const join = await userAndActivity.findUserAndActivity(data)
  let arr = []
  for (let item of join) {
    arr.push(item.activityId)
  }
  const result = await activity.findActivity({_id: arr})
  for (let item of result) {
    item.nickName = (await wxUser.findWxUser({id:item.userId}))[0].nickName
    item.img1 = baseUrl + '/images/activityImages/' + item.img1
    item.img2 = baseUrl + '/images/activityImages/' + item.img2
    item.img3 = baseUrl + '/images/activityImages/' + item.img3
  }
  ctx.body = JSON.stringify({code: 200, activityList: result})
})
// 确认活动发布
router.post('/request/confirmActivity', async ctx => {
  const data = ctx.request.body

  const result = await activity.updateActivity({_id: data.id},{status: 1})

  ctx.body = JSON.stringify({code: 200, message: '活动确认成功'})
})
// 删除活动
router.post('/request/deleteActivity', async ctx => {
  const data = ctx.request.body

  const result = await activity.updateActivity({_id: data.id},{status: 2})

  ctx.body = JSON.stringify({code: 200, message: '删除活动成功'})
})

// 导出信息
router.post('/request/getExportActivity', async ctx => {
  const data = ctx.request.body

  // 获取报名表
  const result = await userAndActivity.findUserAndActivity({activityId: data.activityId})

  if (result.length === 0) {
    ctx.body = JSON.stringify({code: 506, message: '无导出数据'})
    return 
  }

  // 获取详细信息
  const activityData = (await activity.findActivity({_id: result[0].activityId}))[0]
  const activityName = activityData.activityName
  const activityTime = activityData.activityTime
  const activityTarget = activityData.activityTarget
  const activityContent = activityData.activityContent
  let arr = []
  for (const item of result) {
    let obj = {}
    const userData = (await wxUser.findWxUser({_id: item.userId}))[0]
    obj.nickName = userData.nickName
    obj.studentId = userData.studentId
    obj.name = userData.name

    obj.activityName = activityName
    obj.activityTime = activityTime
    obj.activityTarget = activityTarget
    obj.activityContent = activityContent

    arr.push(obj)
  }

  // 初始化excel表格
  const workbook = new Excel.Workbook()
  workbook.creator = 'admin'
  workbook.lastModifiedBy = 'admin'
  workbook.created = new Date()
  workbook.modified = new Date()

  // 生成报表
  const name = activityName + '报名表_'+new Date().toISOString().split('T')[0]+'_' + parseInt(Math.random()* 10**10)
  let sheet = workbook.addWorksheet(name)

  sheet.columns = [
    {header: '昵称', key: 'nickName'},
    {header: '学号', key: 'studentId'},
    {header: '名字', key: 'name'},
    {header: '活动名', key: 'activityName'},
    {header: '活动时间', key: 'activityTime'},
    {header: '活动对象', key: 'activityTarget'},
    {header: '活动内容', key: 'activityContent'},
  ]

  sheet.addRows(arr)

  // 保存excel文件
  const filePath = './static/excel/'+name+'.xlsx'
  await workbook.xlsx.writeFile(filePath).then( async () => {
    ctx.body = JSON.stringify({code: 200, excelUrl: baseUrl + filePath.replace('./static','') })
  }, function (err) {
    console.log(err)
    ctx.body = JSON.stringify({code: 506, message: '生成表格失败'})
  })
})


// 获取商品
router.get('/request/getGoods', async ctx => {
  const result = await goods.findGoods({})
  for (const item of result) {
    item.img = baseUrl + '/images/goodsImages/' + item.img
  }
  ctx.body = JSON.stringify({code: 200, goodsList: result})
})
// 保存商品
router.post('/request/saveGoods', async ctx => {
  const data = ctx.request.body
    // 随机数作为图片保存的名字
    const range = parseInt(Math.random() * 10**10)
    // 获取图片类型
    const type = data.img.match(/data:image\/(.+);base64,/)[1]
    // 保存图片到本地
    saveBase64Image(data.img,'./static/images/goodsImages/',range+'.'+type)
    // 转换名字
    data.img = range+'.'+type
  const result = await goods.saveGoods({name: data.name,price: data.price, img: data.img})
  ctx.body = JSON.stringify({code: 200, message: '保存商品成功'})
})
// 删除商品
router.post('/request/deleteGoods', async ctx => {
  const data = ctx.request.body

  const result = await goods.deleteGoods({_id: data.id})

  ctx.body = JSON.stringify({code: 200, message: '删除商品成功'})
})

// 获取意见
router.get('/request/getOpinion', async ctx => {
  const result = await opinion.findOpinion({})
  for (const item of result) {
    item.nickName = (await wxUser.findWxUser({id: item.userId}))[0].nickName
  }
  ctx.body = JSON.stringify({code: 200, opinionList: result})
})
// 保存意见
router.post('/request/saveOpinion', async ctx => {
  const data = ctx.request.body
  const result = await opinion.saveOpinion(data)
  ctx.body = JSON.stringify({code: 200, message: '保存商品成功'})
})

// 获取轮播图
router.get('/request/getGraph', async ctx => {
  const result = await graph.findGraph({})
  for (const item of result) {
    if (item.img) item.img = baseUrl + '/images/graphImages/' + item.img
  }
  ctx.body = JSON.stringify({code: 200, graphList: result})
})
// 保存轮播图
router.post('/request/updateGraph', async ctx => {
  const data = ctx.request.body

  if (data.img !== '') {
    // 随机数作为图片保存的名字
    const range = parseInt(Math.random() * 10**10)
      // 获取图片类型
    const type = data.img.match(/data:image\/(.+);base64,/)[1]
    // 保存图片到本地
    saveBase64Image(data.img,'./static/images/graphImages/',range+'.'+type)
    // 转换名字
    data.img = range+'.'+type
  }
  const t = await graph.findGraph({ordinal: data.ordinal})
  if (t.length === 0) {
    const result = await graph.saveGraph(data)
  }else {
    const result = await graph.updateGraph({ordinal: data.ordinal}, data)
  }
  
  ctx.body = JSON.stringify({code: 200, message: '保存轮播图成功'})
})

// 获取积分
router.get('/request/getIntegral', async ctx => {
  const result = await integral.findIntegral({})
  
  for (const item of result) {
    item.nickName = (await wxUser.findWxUser({id: item.userId}))[0].nickName
  }

  ctx.body = JSON.stringify({code: 200, integralList: result})
})
// 保存积分
router.post('/request/saveIntegral', async ctx => {
  const data = ctx.request.body

  await wxUser.updateWxUser({_id: data.userId},{integral: data.integral})

  const result = await integral.saveIntegral(data)
  
  ctx.body = JSON.stringify({code: 200, message: '保存积分记录成功'})
})


// 获取分类
router.get('/request/getClassify', async ctx => {
  const result = await classify.findClassify({})

  ctx.body = JSON.stringify({code: 200, classifyList: result})
})
// 保存分类
router.post('/request/saveClassify', async ctx => {
  const data = ctx.request.body

  const result = await classify.saveClassify(data)
  
  ctx.body = JSON.stringify({code: 200, message: '保存分类成功'})
})
// 删除分类
router.post('/request/deleteClassify', async ctx => {
  const data = ctx.request.body

  const result = await classify.deleteClassify({_id: data.id})
  
  ctx.body = JSON.stringify({code: 200, message: '删除分类成功'})
})

// 获取扫描数据
router.get('/request/getScan', async ctx => {
  const result = await scan.findScan({})

  for (const item of result) {
    item.nickName = (await wxUser.findWxUser({id: item.userId}))[0].nickName
  }

  ctx.body = JSON.stringify({code: 200, scanList: result})
})
// 保存扫描数据
router.post('/request/saveScan', async ctx => {
  const data = ctx.request.body

  const result = await scan.saveScan(data)

  ctx.body = JSON.stringify({code: 200, message: '保存扫描数据成功'})
})


// 常量
const AppID = 'wx97c9e7f51f3cca6b'
const AppSecret = '89c28a5ceb32a8d46189f4d9cfb36ca2'
const grant_type = 'authorization_code'
const wx_url = 'https://api.weixin.qq.com/sns/jscode2session'

// 微信小程序登录
router.post('/request/wxLogin', async (ctx)=>{
  // 微信小程序传来的数据
  let data = ctx.request.body
  // 获取用户唯一id
  const result = await axios.get(wx_url+'?appid='+AppID+'&secret='+AppSecret+"&js_code="+data.code+'&grant_type='+grant_type)

  // 判断是否正常获取openid
  if (result.data.openid === undefined) {
    ctx.body = JSON.stringify({code: 506, message: '密钥不正常'})
    return
  }

  // 尝试从数据库获取该用户数据
  let userArr = await wxUser.findWxUser({openid: result.data.openid})

  // 没有该用户数据，创建用户
  if (userArr.length === 0) {
    userArr = [await wxUser.saveWxUser({openid:result.data.openid,nickName:data.nickName,avatarUrl:data.avatarUrl,integral:0})]
  } 
  
  ctx.body = JSON.stringify({code: 200, message: '登录成功',userInfo: userArr[0]})
})

router.get('/request/clearAll', async ctx => {
  // 初始化数据库数据
  await wxUser.deleteWxUser({})
  await subscribe.deleteSubscribe({})
  await activity.deleteActivity({})
  await userAndActivity.deleteUserAndActivity({})
  await goods.deleteGoods({})
  await opinion.deleteOpinion({})
  await graph.deleteGraph({})
  await integral.deleteIntegral({})
  await classify.deleteClassify({})
  await scan.deleteScan({})

  // 清空文件
  // excel文件夹
  for (const item of fs.readdirSync('./static/excel')) {
    fs.unlinkSync('./static/excel/'+item)
  }
  // activityImages文件夹
  for (const item of fs.readdirSync('./static/images/activityImages')) {
    fs.unlinkSync('./static/images/activityImages/'+item)
  }
  // goodsImages文件夹
  for (const item of fs.readdirSync('./static/images/goodsImages')) {
    fs.unlinkSync('./static/images/goodsImages/'+item)
  }
  // graphImages文件夹
  for (const item of fs.readdirSync('./static/images/graphImages')) {
    fs.unlinkSync('./static/images/graphImages/'+item)
  }
  ctx.body = JSON.stringify({code: 200, message: '初始化成功'})
})

//  导出
module.exports = router